package com.example.sqlitehelper;

import java.util.List;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class DBHelper {

	public static DBHelper INSTANCE = null;

	static String sql = "";

	static SQLiteDatabase sqliteDatabase = new SQLiteHelper(
			MainActivity.context, "AppSQLite", 1).getWritableDatabase();

	public static DBHelper getInstance() {
		if (INSTANCE == null) {
			INSTANCE = new DBHelper();
		}
		return INSTANCE;
	}

	public static boolean createTable(String tableName, List<String> attributes) {

		StringBuffer bufferAttribute = new StringBuffer();

		for (int i = 0; i < attributes.size(); i++) {
			if (i == (attributes.size() - 1)) {
				bufferAttribute.append(attributes.get(i));
			} else {
				bufferAttribute.append(attributes.get(i) + " ,");
			}
		}

		String sql = "create table if not exists " + tableName
				+ "(_id integer primary key autoincrement,"
				+ bufferAttribute.toString() + ")";
		Log.i("gjf", "createtable   " + sql);

		sqliteDatabase.execSQL(sql);

		return true;
	}

	public static DBHelper select(String select) {
		if (sql.length() == 0) {
			sql += " select " + select;
		}
		return getInstance();
	}

	public static DBHelper from(String from) {
		sql += " from " + from;

		return getInstance();
	}

	public static DBHelper where(String where) {
		sql += " where " + where;
		
		return getInstance();
	}

	public static DBHelper orderby(String orderby) {
		sql += " order by " + orderby;
		
		return getInstance();
	}

	public static DBHelper insert(String insert) {
		sql += "insert into  " + insert;
		
		return getInstance();
	}

	public static DBHelper values(List<String> values) {
		sql += " values  ( null, '";
		for (int i = 0; i < values.size(); i++) {
			if (i == values.size() - 1) {
				sql += values.get(i) + "')";
			} else {
				sql += values.get(i) + "' ,'";
			}
		}

		return getInstance();
	}

	public static DBHelper delete(String delete) {
		sql += "delete  from " + delete;
		
		return getInstance();
	}

	public static DBHelper drop(String drop) {
		sql += "drop table " + drop;
		
		return getInstance();
	}

	public static Cursor begin() {
		if (sql.contains("select")) {
			Cursor result = sqliteDatabase.rawQuery(sql, null);
			sql = "";
			return result;
		} else {
			sqliteDatabase.execSQL(sql);
			sql = "";
		}
		
		return null;
	}

}
